package com.smc.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;

/** @author zouqinghua date 2016年1月23日 下午11:38:42 */
public class FileUtils extends org.apache.commons.io.FileUtils{

	/**
     * 生成随机文件名
     * @return
     */
    public static String generateFileName() {
        return UUID.randomUUID().toString();
    }
    
	 /**
     * 写入文件
     * @param target
     * @param src
     * @throws IOException
     */
    public static void write(String target, InputStream src) throws IOException {
        OutputStream os = new FileOutputStream(target);
        byte[] buf = new byte[1024];
        int len;
        while (-1 != (len = src.read(buf))) {
            os.write(buf,0,len);
        }
        os.flush();
        os.close();
        src.close();
    }
    
    /**
     * 分块写入文件
     * @param target
     * @param targetSize
     * @param src
     * @param srcSize
     * @param chunks
     * @param chunk
     * @throws IOException
     */
    public static void writeWithBlok(String target, Long targetSize, InputStream src, Long srcSize, Integer chunks, Integer chunk) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(target,"rw");
        randomAccessFile.setLength(targetSize);
        if (chunk == chunks - 1 && chunk != 0) {
            randomAccessFile.seek(chunk * (targetSize - srcSize) / chunk);
        } else {
            randomAccessFile.seek(chunk * srcSize);
        }
        byte[] buf = new byte[1024];
        int len;
        while (-1 != (len = src.read(buf))) {
            randomAccessFile.write(buf,0,len);
        }
        randomAccessFile.close();
    }
	
  /**
   * 名称转码
   *
   * @param url URL
   * @return
   */
  public static String EncodeURLFileName(String url) {
    String newUrl = "";
    if (!StringUtils.isEmpty(url)) {
      String path = url.substring(0, url.lastIndexOf("/") + 1);
      String outName = url.substring(url.lastIndexOf("/") + 1);
      newUrl = path + Encodes.urlEncode(outName);
    }
    return newUrl;
  }

  /**
   * 修复路径，将 \\ 或 / 等替换为 File.separator
   *
   * @param path
   * @return
   */
  public static String path(String path) {
    String p = StringUtils.replace(path, "\\", "/");
    p = StringUtils.join(StringUtils.split(p, "/"), "/");
    if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
      p += "/";
    }
    if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
      p = p + "/";
    }
    return p;
  }

  public static String filePath(String path) {
    String newPath = "/" + path(path);
    if ("/".equals(newPath.substring(newPath.length() - 1))) {
      newPath = newPath.substring(0, newPath.length() - 1);
    }
    return newPath;
  }

  /**
   * @param duration 毫秒ms
   * @return
   */
	public static String getFormatDuration(Long duration) {
		String showName = "";
		if (duration != null) {
			showName = "";
			long days = duration / (1000 * 60 * 60 * 24);
			long hours = (duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
			long minutes = (duration % (1000 * 60 * 60)) / (1000 * 60);
			long seconds = (duration % (1000 * 60)) / 1000;
			//showName = days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
			if(days>0){
				showName +=days+"天";
			}
			if(hours>0){
				showName +=hours+"小时";
			}
			if(minutes>0){
				showName +=minutes+"分钟";
			}
			if(seconds>0){
				showName +=seconds+"秒";
			}
			
		}
		return showName;
	}
  
	public static String getFormatBitRate(Long bitRate) {
		String showName = "";
		if(bitRate!=null){
			double kiloByte = bitRate / 1000.0;
		    double megaByte = kiloByte / 1000;
		      BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
		      showName =  result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "kbps";
		}
		return showName;
	}
	
  
 /**
  * @param size 比特 bytes
  * @return
  */
  public static String getFormatSize(Long size) {
	  if(size == null){
		  
		  return "";
	  }
    double kiloByte = size / 1024.0;
    if (kiloByte < 1) {
      return size + "Byte(s)";
    }

    double megaByte = kiloByte / 1024;
    if (megaByte < 1) {
      BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
      return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
    }

    double gigaByte = megaByte / 1024;
    if (gigaByte < 1) {
      BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
      return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
    }

    double teraBytes = gigaByte / 1024;
    if (teraBytes < 1) {
      BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
      return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
    }
    BigDecimal result4 = new BigDecimal(teraBytes);
    return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
  }

  public static String getFileType(String fileName) {
    String type = "";
    if (StringUtils.isNotBlank(fileName)) {
      try {
        type = fileName.substring(fileName.lastIndexOf(".") + 1);
        type = type.toLowerCase(); //类型小写
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return type;
  }

  public static String getFileNamePrefix(String fileName) {
    String name = "";
    if (StringUtils.isNotBlank(fileName)) {
      try {
        if (fileName.indexOf("/") >= 0) {
          name = fileName.substring(fileName.lastIndexOf("/") + 1);
        }else {
        	name = fileName;
        }
        if (name.indexOf(".") >= 0) {
          name = name.substring(0, name.lastIndexOf("."));
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return name;
  }

  public static String getNameByKey(String key) {
    String name = "";
    if (!StringUtils.isEmpty(key)) {
      name = key.substring(key.lastIndexOf("/") + 1);
    }
    return name;
  }
  
  public static String getMd5(String prestr){
	  String mysign = null;
	  if(StringUtils.isNotBlank(prestr)){
		  try {
	          mysign = DigestUtils.md5Hex(prestr.getBytes("UTF-8"));
	      } catch (UnsupportedEncodingException e) {
	          throw new RuntimeException("生成MD5过程中出现错误,指定的编码集错误");
	      }
	  }
      return mysign;
  }
  
	public static String getMd5(Object object) {
		String mysign = null;
		if (object != null) {
			if (object instanceof InputStream) {
				InputStream inputStream = (InputStream) object;
				try {
					mysign = DigestUtils.md5Hex(inputStream);
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					try {
						if(inputStream!=null){
							inputStream.close();
						}
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			} else if (object instanceof File) {
				File file = (File) object;
				if (file != null && file.exists()) {
					InputStream inputStream = null;
					try {
						inputStream = new FileInputStream(file);
					} catch (FileNotFoundException e) {
						throw new RuntimeException("文件不存在");
					}
					try {
						mysign = DigestUtils.md5Hex(inputStream);
					} catch (IOException e) {
						e.printStackTrace();
					}finally {
						try {
							if(inputStream!=null){
								inputStream.close();
							}
						} catch (Exception e2) {
							e2.printStackTrace();
						}
					}
				}
			} else {
				String prestr = JsonUtils.toJSONString(object);
				try {
					byte[] data1 = prestr.getBytes("UTF-8");
					mysign = DigestUtils.md5Hex(data1);
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("生成MD5过程中出现错误,指定的编码集错误");
				}
			}

		}
		return mysign;
	}
  
  public static String getMd5ByInputStream(InputStream inputStream){
  	String md5 = null;
  	if(inputStream!=null){
  		try {
  			md5 = DigestUtils.md5Hex(inputStream);
  			System.out.println("MD5:" + md5);
  		} catch (IOException e) {
  			e.printStackTrace();
  		}
  	}
	return md5;
  }
  
  public static String getMd5ByFile(File file){
  	String md5 = null;
  	if(file!=null && file.exists()){
  		try {
  			md5 = DigestUtils.md5Hex(new FileInputStream(file));
  			System.out.println("MD5:" + md5);
  		} catch (IOException e) {
  			e.printStackTrace();
  		}
  	}
	return md5;
  }
}
